package com.whl.cloud.filter;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StreamUtils;

import com.google.gson.Gson;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.whl.cloud.constant.ZuulConstant;

@Component
public class RequstFilter extends ZuulFilter {
	private static Log log = LogFactory.getLog(RequstFilter.class);

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext curContext = RequestContext.getCurrentContext();
		HttpServletRequest request = curContext.getRequest();
		Map<String, String[]> reqMap = request.getParameterMap();
		if (log.isInfoEnabled()) {
			String requestId = curContext.get("requestId").toString();
			if (CollectionUtils.isEmpty(reqMap) == false) {
				log.info("requestId = " + requestId + "\n" + new Gson().toJson(reqMap));
			}
			try {
				String contentType = request.getHeader("Content-Type");
				if (contentType != null && contentType.startsWith("multipart")) {
					log.info("requestId = " + requestId + "\n" + contentType);
				} else {
					InputStream stream = curContext.getRequest().getInputStream();
					if (stream != null) {
						String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
						log.info("requestId = " + requestId + "\n" + body);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public String filterType() {
		return ZuulConstant.FILTER_TYPE_PRE;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

}
